import cn.edu.swu.ImageDownloader.ImageManager;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        ImageManager manager = new ImageManager();

        // 使用try-with-resources自动关闭Scanner
        try (Scanner scanner = new Scanner(System.in)) {
            boolean running = true;

            System.out.println("欢迎使用图片下载系统！");

            while (running) {
                // 显示菜单
                System.out.println("\n=== 图片下载系统 ===");
                System.out.println("1. 下载图片");
                System.out.println("2. 查看所有图片");
                System.out.println("3. 搜索图片");
                System.out.println("4. 修改图片名称"); // new: 新增菜单选项
                System.out.println("5. 删除图片");
                System.out.println("6. 退出");
                System.out.print("请输入选项 (1-6): ");

                // 处理用户输入
                int choice;
                try {
                    String input = scanner.nextLine().trim();
                    if (input.isEmpty()) {
                        System.out.println("请输入有效的数字选项");
                        continue;
                    }
                    choice = Integer.parseInt(input);
                } catch (NumberFormatException e) {
                    System.out.println("请输入有效的数字选项 (1-6)");
                    continue;
                }

                // 根据选项执行相应功能
                switch (choice) {
                    case 1:
                        handleDownload(manager, scanner);
                        break;
                    case 2:
                        manager.listImages();
                        break;
                    case 3:
                        handleSearch(manager, scanner);
                        break;
                    case 4: // new: 处理重命名
                        handleRename(manager, scanner);
                        break;
                    case 5:
                        handleDelete(manager, scanner);
                        break;
                    case 6:
                        running = false;
                        System.out.println("感谢使用，再见！");
                        break;
                    default:
                        System.out.println("请输入1-6之间的数字");
                }
            }
        }
    }

    // 处理下载图片逻辑
    private static void handleDownload(ImageManager manager, Scanner scanner) {
        System.out.print("请输入图片URL (输入q取消): ");
        String url = scanner.nextLine().trim();

        if (url.equalsIgnoreCase("q")) {
            System.out.println("已取消下载");
            return;
        }

        // 简单校验URL格式
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            System.out.println("请输入有效的URL（以http://或https://开头）");
            return;
        }

        manager.downloadImage(url, scanner); // 传递scanner用于下载后的重命名输入
    }

    // new: 处理重命名逻辑
    private static void handleRename(ImageManager manager, Scanner scanner) {
        manager.listImages(); // 先显示所有图片
        System.out.print("请输入要修改的图片原名（输入q取消）：");
        String oldName = scanner.nextLine().trim();

        if (oldName.equalsIgnoreCase("q")) {
            System.out.println("已取消重命名");
            return;
        }

        System.out.println("提示：建议按分类命名（如'风景_日出.jpg'、'头像_卡通.png'）");
        System.out.print("请输入新文件名（含扩展名）：");
        String newName = scanner.nextLine().trim();
        manager.renameImage(oldName, newName);
    }

    // 处理搜索图片逻辑
    private static void handleSearch(ImageManager manager, Scanner scanner) {
        System.out.print("请输入要搜索的关键词（输入q取消）：");
        String keyword = scanner.nextLine().trim();

        if (keyword.equalsIgnoreCase("q")) {
            System.out.println("已取消搜索");
            return;
        }

        List<String> matches = manager.searchImage(keyword);

        if (matches.isEmpty()) {
            return; // 无匹配结果，直接返回
        }

        System.out.print("请输入序号选择图片（输入0取消）：");
        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            if (choice < 0 || choice > matches.size()) {
                System.out.println("无效的序号");
                return;
            }
            if (choice == 0) {
                System.out.println("已取消选择");
                return;
            }

            // 获取用户选择的图片名
            String selectedName = matches.get(choice - 1);
            System.out.println("你选择了：" + selectedName);

            // 处理选中图片后的操作
            handleSelectedImage(manager, scanner, selectedName);
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字");
        }
    }

    // new: 处理选中图片后的操作
    private static void handleSelectedImage(ImageManager manager, Scanner scanner, String fileName) {
        System.out.println("\n请选择操作：");
        System.out.println("1. 打开图片");
        System.out.println("2. 重命名图片");
        System.out.println("3. 删除图片");
        System.out.println("4. 返回");
        System.out.print("请输入选项：");

        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            switch (choice) {
                case 1:
                    openImage(manager.getImagePath(fileName));
                    break;
                case 2:
                    System.out.print("请输入新文件名（含扩展名）：");
                    String newName = scanner.nextLine().trim();
                    manager.renameImage(fileName, newName);
                    break;
                case 3:
                    System.out.print("确定要删除 " + fileName + " 吗? (y/n): ");
                    String confirm = scanner.nextLine().trim().toLowerCase();
                    if (confirm.equals("y") || confirm.equals("yes")) {
                        manager.deleteImage(fileName);
                    } else {
                        System.out.println("已取消删除");
                    }
                    break;
                case 4:
                    System.out.println("返回主菜单");
                    break;
                default:
                    System.out.println("请输入1-4之间的数字");
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字");
        }
    }

    // new: 打开图片（调用系统默认程序）
    private static void openImage(String path) {
        if (path == null) {
            System.out.println("图片路径不存在");
            return;
        }

        File file = new File(path);
        if (!file.exists()) {
            System.out.println("图片文件不存在");
            return;
        }

        try {
            Desktop.getDesktop().open(file);
            System.out.println("正在打开图片...");
        } catch (IOException e) {
            System.out.println("打开图片失败：" + e.getMessage());
        }
    }

    // 处理删除图片逻辑
    private static void handleDelete(ImageManager manager, Scanner scanner) {
        manager.listImages();
        System.out.print("请输入要删除的图片名称 (输入q取消): ");
        String name = scanner.nextLine().trim();

        if (name.equalsIgnoreCase("q")) {
            System.out.println("已取消删除");
            return;
        }

        // 二次确认
        System.out.print("确定要删除 " + name + " 吗? (y/n): ");
        String confirm = scanner.nextLine().trim().toLowerCase();

        if (confirm.equals("y") || confirm.equals("yes")) {
            manager.deleteImage(name);
        } else {
            System.out.println("已取消删除");
        }
    }
}
